#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include "RingQueue.hpp"
#include "Task.hpp"
using namespace std;

#define CNUM 1
#define PNUM 1

struct ThreadData
{
    // RingQueue<int>* _rq;
    RingQueue<Task>* _rq;
    string _name;
};

void* Productor(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    // RingQueue<int>* rq = td->_rq;
    RingQueue<Task>* rq = td->_rq;
    string name = td->_name;

    while(true)
    {
        // 1. 获取数据
        // int data = rand() % 10 + 1;
        int x = rand() % 10 + 1;
        int y = rand() % 10 + 1;
        char op = opers[rand() % opers.size()];
        Task t(x, y, op);

        // 2. 生产数据
        rq->push(t);
        cout << td->_name << " task done, task is: " << t.GetTask() << endl;
        //sleep(1);
    }   

}


void* Consumer(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    // RingQueue<int>* rq = td->_rq;
    RingQueue<Task>* rq = td->_rq;
    string name = td->_name;

    while(true)
    {
        // 1. 消费数据
        // int data = 0;
        // rq->pop(&data);

        Task t;
        rq->pop(&t);

        // 2. 处理数据    
        t();
        cout << td->_name << " get task, task is: " << t.GetTask() << ", ret: " << t.GetResult() << endl;
        sleep(0.5);
    }
}

int main()
{
    srand(time(nullptr));
    // RingQueue<int>* rq = new RingQueue<int>();
    RingQueue<Task>* rq = new RingQueue<Task>(10); 
    pthread_t c[CNUM], p[PNUM];

    vector<ThreadData*> tds;
    for(int i = 0; i < CNUM; ++i) 
    {
        ThreadData* td = new ThreadData();
        td->_rq = rq;
        td->_name = "Consumer[" + to_string(i) + "]";
        tds.push_back(td);
        pthread_create(c + i, nullptr, Consumer, (void*)td);
    }
    for(int i = 0; i < PNUM; ++i) 
    {
        ThreadData* td = new ThreadData();
        td->_rq = rq;
        td->_name = "Productor[" + to_string(i) + "]";
        tds.push_back(td);
        pthread_create(p + i, nullptr, Productor, (void*)td);
    }
    for(int i = 0; i < CNUM; ++i) pthread_join(c[i], nullptr);
    for(int i = 0; i < PNUM; ++i) pthread_join(p[i], nullptr);
    for(auto& td : tds) delete td;
    delete rq;
    return 0;
}

